#!/bin/sh

. "$SPEC_PATH/abstract/dbops-minor-version-upgrade"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/dbops-major-version-upgrade")"
}

e2e_test_install() {
  CLUSTER_NAME="$(get_sgcluster_name dbops-minor-version-upgrade)"
  DBOPS_NAME="$(get_sgdbops_name minor-version-upgrade)"

  kubectl create namespace "$CLUSTER_NAMESPACE"

  deploy_curl_pod "$CLUSTER_NAMESPACE"

  wait_pods_running "$CLUSTER_NAMESPACE" 1
}

e2e_test() {
  run_test "Checking that minor version upgrade is working" check_minor_version_upgrade_is_working

  run_test "Checking that minor version upgrade in-place is working" check_minor_version_upgrade_in_place_is_working
}

check_minor_version_upgrade_is_working() {
  reset_cluster

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: minorVersionUpgrade
  minorVersionUpgrade:
    postgresVersion: "$E2E_MINOR_TARGET_POSTGRES_VERSION"
EOF

  wait_until eval '[ "$(kubectl get sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME" \
    --template "{{ .status.opRetries }}")" = "0" ]'
  kubectl get sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME" -o yaml > "$LOG_PATH/sgdbops.yaml"
  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
  kubectl create -f "$LOG_PATH/sgdbops.yaml"

  check_minor_version_upgrade

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}

check_minor_version_upgrade_in_place_is_working() {
  reset_cluster

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: minorVersionUpgrade
  minorVersionUpgrade:
    postgresVersion: "$E2E_MINOR_TARGET_POSTGRES_VERSION"
    method: InPlace
EOF

  check_minor_version_upgrade

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}

check_minor_version_upgrade() {
  assert_dbops_running "$DBOPS_NAME" "$CLUSTER_NAMESPACE"

  assert_dbops_completion "$DBOPS_NAME" "$CLUSTER_NAMESPACE" "$((E2E_TIMEOUT * 2))"

  check_mock_data_samehost "$CLUSTER_NAME"
  wait_until check_mock_data_replication "$CLUSTER_NAME"
}
